/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package session.stateless;

import entity.ServicePlan;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.PersistenceContext;

/**
 *
 * @author Jacko
 */
@Stateless
public class ServicePlanSession implements ServicePlanSessionLocal {

    @PersistenceContext
    private EntityManager em;

    public Long addServicePlan(String planName, Double mthFee, Double comm1,
            Double comm2, Double init_Fee, Double perUnitFee) {

        ServicePlan servicePlan = new ServicePlan();
        
        if (!chkExistingPlan(planName, mthFee)) {
   
            servicePlan.setSvcPlanName(planName);
            servicePlan.setSvcPlanMthFee(mthFee);
            servicePlan.setSvcPlancomm1(comm1);
            servicePlan.setSvcPlancomm2(comm2);
            servicePlan.setInitialFee(init_Fee);
            servicePlan.setPerUnitFee(perUnitFee);

            em.persist(servicePlan);
            em.flush();
        }
        return servicePlan.getSvcPlanID(); 
    }

    public List<ServicePlan> modifyServicePlan() {
        
        Query query = em.createQuery("SELECT p FROM ServicePlan p"); 
        //query.setParameter("inPlanName", planName); 
        
        return query.getResultList(); 

    }

    public List<ServicePlan> getAllServicePlan() {
               
        Query query = em.createQuery("SELECT p FROM ServicePlan p");
        return query.getResultList();
    }


    private Boolean chkExistingPlan(String planName, Double mthFee) {
        Query query = em.createQuery("SELECT p FROM ServicePlan p WHERE p.svcPlanName = :planName "
                + "AND p.svcPlanMthFee = :mthFee");
        query.setParameter("planName", planName);
        query.setParameter("mthFee", mthFee);

        List resultList = query.getResultList();
        
        
      

        if (resultList.isEmpty()) {
            return false;
        } else {
            return true;
        }
    }
    
}
